<?php

namespace IDock\Insurance\MACN\Response;

use Exception;
use IDock\Http\Response;
use IDock\Printer\Premium\PremiumInquiryPrinter;
use IDock\Printer\PremiumUnderwritingPrinter;
use IDock\Printer\SpecialClausesPrinter;

class ClauseListResponse extends AllMACNResponse
{

    public function resolve(): Response
    {
        $body = $this->getBody();
        $body = iconv('UTF-8','GBK',$body);
        if ($body) {
            libxml_disable_entity_loader();
            $body = simplexml_load_string($body);
            $body = $this->objectToArray($body);
            $errorCode = $body['head']['statusCode'] ?? '';
            if ($errorCode != 'SUCCESS') {
                $this->setError($body['head']['description'] ?? '未知错误或无错误提示');
                return  $this;
            }

            $this->setBody($body['body'] ?? '');
        }

        return $this;
    }

    public function printerInit(): Response
    {
        $body = $this->getBody();
        $engageList = $body['engages']['engage'] ?? [];
        $premiumUnderwritingPrinter = new PremiumInquiryPrinter();
        if(!$this->isSuccess()){
            $premiumUnderwritingPrinter->success = false;
            $this->printer = $premiumUnderwritingPrinter;
            return $this;
        }
        if(!isset($engageList[0])){
            $tmp = $engageList;
            unset($engageList);
            $engageList[] = $tmp;
            unset($tmp);
        }

        $premiumUnderwritingPrinter = new PremiumInquiryPrinter();
        foreach ($engageList as $val){
            $engage = new SpecialClausesPrinter();
            $engage->clauseName = $val['clauseCode'];
            $engage->clauseCode = $val['clauseNo'];
            $engage->clauseContent = $val['clauses'];
            $engage->autoFlag = '0';
            $engage->riskType = $val['clauseAttribute'] == '1' ? 'TCI' : 'VCI';//交强险固定特约
            $premiumUnderwritingPrinter->specialClausesAppend($engage);
        }


        $this->printer = $premiumUnderwritingPrinter;

        return $this;
    }
}